/*
 * CadastroTurma.java
 *
 * Created on 10 de Junho de 2010, 22:58
 */

package virtual.view;

import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import virtual.BD.Turma;
import virtual.service.TurmaJpaController;
import virtual.service.exceptions.NonexistentEntityException;

/**
 *
 * @author Onyas D. Claudio
 */
public class CadastroTurma extends javax.swing.JPanel {

    private TurmaJpaController service;
    
    /** Creates new form CadastroTurma */
    public CadastroTurma() {
        initComponents();
        
        service = new TurmaJpaController();
    } // Fim do construtor
    
    /** Creates new form CadastroTurma */
    public CadastroTurma(Turma turma) {
        initComponents();
        
        service = new TurmaJpaController();
        
        this.preencherTurma(turma);
    } // Fim do construtor
    
    
    /**
     * Preenche os campos com uma turma.
     * @param turma turma que preenche os campos.
     */
    public void preencherTurma(Turma turma) {
        
        this.jtfCodigo.setText(turma.getCdTurma().toString());
        this.jtfNomeTurma.setText(turma.getNmTurma());
        
        this.jtfDataInicio.setText(dataParaString(turma.getDtInicioTurma()));
        this.jtfDataFim.setText(dataParaString(turma.getDtFimTurma()));
        
        this.jcbDisciplina.setSelectedIndex(turma.getCdDisciplina());
        this.jcbProfessor.setSelectedIndex(turma.getCdProfessor());
        
    } // Fim do método preencherTurma
    
    
    /**
     * Converte um tipo Date para String.
     * @param data Data a ser formatada.
     * @return String formatada.
     */
    public String dataParaString(Date data) {
        
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(data);
        String format = gc.get(GregorianCalendar.DAY_OF_MONTH)+"/"+(gc.get(GregorianCalendar.MONTH)+1)+"/"+gc.get(GregorianCalendar.YEAR);
        return format;
        
    } // Fim do método dataParaString
    

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jtfCodigo = new javax.swing.JTextField();
        jtfNomeTurma = new javax.swing.JTextField();
        jtfDataInicio = new javax.swing.JTextField();
        jtfDataFim = new javax.swing.JTextField();
        jcbProfessor = new javax.swing.JComboBox();
        jcbDisciplina = new javax.swing.JComboBox();
        jbSalvar = new javax.swing.JButton();
        jbPesquisar = new javax.swing.JButton();
        jbExcluir = new javax.swing.JButton();

        jLabel1.setText("Codigo: ");
        jLabel1.setName("jlCodigo"); // NOI18N

        jLabel2.setText("Nome: ");
        jLabel2.setName("jlNomeTurma"); // NOI18N

        jLabel3.setText("Data de início: ");
        jLabel3.setName("jlDataInicio"); // NOI18N

        jLabel4.setText("Data de término: ");
        jLabel4.setName("jlDataFinal"); // NOI18N

        jLabel5.setText("Professor:");
        jLabel5.setName("jlProfessor"); // NOI18N

        jLabel6.setText("Disciplina:");
        jLabel6.setName("jlDisciplina"); // NOI18N

        jtfCodigo.setEnabled(false);
        jtfCodigo.setName("jtfCodigo"); // NOI18N

        jtfNomeTurma.setName("jtfNomeTurma"); // NOI18N

        jtfDataInicio.setName("jtfDataInicio"); // NOI18N

        jtfDataFim.setName("jtfDataFim"); // NOI18N

        jcbProfessor.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Arnaldo César Coelho", "Carlos Eugênio Simon", "Claudio Marsiglia", "Dalmo Bozzano", "José Roberto Whritg" }));
        jcbProfessor.setName("jcbProfessor"); // NOI18N

        jcbDisciplina.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Algoritmos I", "Algoritmos II", "Banco de Dados I", "Banco de Dados II", "Banco de Dados Aplicado", "Ciência e Pesquisa", "Engenharia de Software I", "Engenharia de Software II", "Engenharia de Software III", "Filosofia", "Programação I", "Programação II", "Programação para Web", "Probabilidade e Estatística" }));
        jcbDisciplina.setName("jcbDisciplina"); // NOI18N

        jbSalvar.setText("Salvar");
        jbSalvar.setToolTipText("Salva o regristro");
        jbSalvar.setName("jbSalvar"); // NOI18N
        jbSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbSalvarActionPerformed(evt);
            }
        });

        jbPesquisar.setText("Pesquisar");
        jbPesquisar.setToolTipText("Abre tela de pesquisa");
        jbPesquisar.setName("jbPesquisar"); // NOI18N
        jbPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbPesquisarActionPerformed(evt);
            }
        });

        jbExcluir.setText("Excluir");
        jbExcluir.setToolTipText("Exclui o registro");
        jbExcluir.setName("jbExcluir"); // NOI18N
        jbExcluir.setVisible(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jbExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(2, 2, 2))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(18, 18, 18)
                                .addComponent(jtfNomeTurma, javax.swing.GroupLayout.DEFAULT_SIZE, 463, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtfCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addComponent(jLabel6)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jcbDisciplina, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addComponent(jLabel5)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jcbProfessor, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addComponent(jLabel3)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jtfDataInicio, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(jLabel4)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtfDataFim, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap(51, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jtfCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jtfNomeTurma, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jtfDataInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(jtfDataFim, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jcbProfessor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jcbDisciplina, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 103, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbSalvar)
                    .addComponent(jbPesquisar)
                    .addComponent(jbExcluir))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Cadastra ou altera um registro.
     * @param evt evento de ação.
     */
    private void jbSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSalvarActionPerformed

        try {
            
        Turma turma = new Turma();
        // Seta a turma com os dados do cadastro
        turma.setNmTurma(this.jtfNomeTurma.getText());
        // Transforma a data inicial
        int diaI = Integer.parseInt(this.jtfDataInicio.getText().split("/")[0]);
        int mesI = Integer.parseInt(this.jtfDataInicio.getText().split("/")[1])-1;
        int anoI = Integer.parseInt(this.jtfDataInicio.getText().split("/")[2]);
        // Transforma a data final
        int diaF = Integer.parseInt(this.jtfDataFim.getText().split("/")[0]);
        int mesF = Integer.parseInt(this.jtfDataFim.getText().split("/")[1])-1;
        int anoF = Integer.parseInt(this.jtfDataFim.getText().split("/")[2]);
        // Cria as datas
        GregorianCalendar dataInicio = new GregorianCalendar(anoI, mesI, diaI);
        GregorianCalendar dataFim = new GregorianCalendar(anoF, mesF, diaF);
        turma.setDtInicioTurma(dataInicio.getTime());
        turma.setDtFimTurma(dataFim.getTime());
        turma.setCdDisciplina(jcbDisciplina.getSelectedIndex());
        turma.setCdProfessor(jcbProfessor.getSelectedIndex());

        if (this.jtfCodigo.getText().equals("")) {
            service.create(turma);
            JOptionPane.showMessageDialog(this, turma.getNmTurma() + " foi cadastrado com sucesso!", "Salvar", JOptionPane.INFORMATION_MESSAGE);
        } else {
            turma.setCdTurma(Integer.parseInt(this.jtfCodigo.getText()));
            try {
                service.edit(turma);
                JOptionPane.showMessageDialog(this, turma.getNmTurma() + " foi alterado com sucesso!", "Alterar", JOptionPane.INFORMATION_MESSAGE);
            } catch (NonexistentEntityException nee) {
                Logger.getLogger(CadastroPessoa.class.getName()).log(Level.SEVERE, null, nee);
            } catch (Exception e) {
                Logger.getLogger(CadastroPessoa.class.getName()).log(Level.SEVERE, null, e);
            } // Fim do try/catch
        } // Fim do if/else
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Não foi possível salvar.", "Erro ao cadastrar Turma!", JOptionPane.ERROR_MESSAGE);
        System.err.println("ERRO em CadastroTurma.btnCadastrarTurmaActionPerformed(java.awt.event.ActionEvent):\n" + e);
    } // Fim do try/catch

    }//GEN-LAST:event_jbSalvarActionPerformed

/**
 * Fecha a janela atual e abre a tela de pesquisa.
 * @param evt
 */
private void jbPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbPesquisarActionPerformed
    
    PesquisarTurma jp = new PesquisarTurma();
    
    Principal.abreNovaJanelaInterna(jp);
    
}//GEN-LAST:event_jbPesquisarActionPerformed

    
    /**
     * Cadastra uma turma no banco de dados.
     * @param evt evento de ação.
     */

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JButton jbExcluir;
    private javax.swing.JButton jbPesquisar;
    private javax.swing.JButton jbSalvar;
    private javax.swing.JComboBox jcbDisciplina;
    private javax.swing.JComboBox jcbProfessor;
    private javax.swing.JTextField jtfCodigo;
    private javax.swing.JTextField jtfDataFim;
    private javax.swing.JTextField jtfDataInicio;
    private javax.swing.JTextField jtfNomeTurma;
    // End of variables declaration//GEN-END:variables

}
